<?php
namespace App\Controller\App;

use App\Query\ConfigQuery;
use App\Query\UserOutQuery;
use App\Repository\UserOutRepository;
use App\Request\UserOutRequest;

use App\Service\Code\CodeService;

class UserOutController extends Controller
{
    // 日志
    public function index()
    {
        return UserOutQuery::user($this->auth())->paginate(15)->toArray();
    }
    
    // 提现
    public function to(UserOutRequest $request)
    {
        $user = $this->auth();
        
        $config = ConfigQuery::get();
        
        if(!(new CodeService($user->phone))->check($this->input('code')))
        {
            $this->error('code');
        }

        // 金额
        $money = (int) $this->input('money');
        
        // 倍数
        if(!$money || $money % $config['out'])
        {
            $this->error('double');
        }
        
        // 减资产
        if($user->makeMoney('money', $money, '申请提现'))
        {
            // 税
            $tax = ConfigQuery::bi($config, 'out_tax', $money);
            
            // 记录
            UserOutRepository::make()->create($user, array_merge($request->validated(), [
                'money' => $money,
                'tax'   => $tax,
                'total' => bcsub($money, $tax, 2)
            ]));
        
            $this->message('ok');
        }
        
        $this->error('money');
    }
}
